package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.example.common.CacheName;
import com.example.common.R;
import com.example.mapper.DepartmentMapper;
import com.example.pojo.Department;
import com.example.util.DepartmentListener;
import com.example.util.ExcelUtil;
import com.example.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ：伍绍恒
 * @date ：Created in 2022/12/12 14:55
 * @description：
 * @modified By：
 */
@Slf4j
@ResponseBody
@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    RedisUtil redisUtil;

    @GetMapping("/getPage")
    public R<PageInfo> getPage(int page, int pageSize) {
        //启用分页
        PageHelper.startPage(page, pageSize, true);
        //封装分页信息
        PageInfo pageInfo = new PageInfo(departmentMapper.getAllDepartment());
        return R.success(pageInfo);
    }

    //启用缓存
    @GetMapping("/getAll")
    public R<PageInfo> getAll() {

        //封装分页信息
        PageInfo pageInfo = new PageInfo(getDataByCache());
        return R.success(pageInfo);
    }

    //通过excel导入数据
    @PostMapping("/importExcel")
    public R<String> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
//        System.out.println("接收成功"+file);
        if (file.isEmpty()) {
            return R.error("导入失败！");
        }
        try {
            EasyExcel.read(file.getInputStream(), Department.class, new DepartmentListener(departmentMapper)).sheet().doRead();
        } catch (Exception e) {
            return R.error("导入失败！");
        }
        return R.success("导入数据成功！");
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //1获取数据
//            List<Department> departments = departmentMapper.getAllDepartment();
        ExcelUtil excelUtil = new ExcelUtil();
        //2创建excel表
        excelUtil.export("department", getDataByCache(), response);
    }

    @DeleteMapping
    public R<String> delete(String deId) {
        if (departmentMapper.deleteDepartmentById(deId) == 1) {
            //删除旧缓存
            redisUtil.del(CacheName.DEPARTMENT_REDIS.getName());
            return R.success("删除成功！");
        }
        return R.success("删除失败！请重试");
    }

    @PostMapping("/add")
    public R<String> add(@RequestBody Department department) {
        if (departmentMapper.addDepartment(department) == 1) {
            //删除旧缓存
            redisUtil.del(CacheName.DEPARTMENT_REDIS.getName());
            return R.success("添加成功！");
        }
        return R.error("添加失败！请重试");
    }

    @PutMapping("/update")
    public R<String> updateDepartment(@RequestBody Department department) {
        if (departmentMapper.updateDepartmentById(department) == 1) {
            //删除旧缓存
            redisUtil.del(CacheName.DEPARTMENT_REDIS.getName());
            return R.success("修改成功！");
        }
        return R.error("修改失败！请重试");
    }

    //缓存获取类
    public List<Department> getDataByCache() {
        List<Department> allDepartment = null;
        //判断缓存是否已有数据
        String departmentAllData = (String) redisUtil.get(CacheName.DEPARTMENT_REDIS.getName());
        System.out.println(CacheName.DEPARTMENT_REDIS.getName());
        if (departmentAllData != null) {//存在缓存，则直接使用缓存返回
            System.err.println("Using Cache");
            //Json转对象
            allDepartment = JSONUtil.toList(departmentAllData, Department.class);
        } else {
            //为空的话，需要进行数据库查询
            allDepartment = departmentMapper.getAllDepartment();
            //对象转Json,将结果存到缓存中
            redisUtil.set(CacheName.DEPARTMENT_REDIS.getName(), JSONUtil.toJsonStr(allDepartment), 10);
        }
        return allDepartment;
    }
}
